package com.example.mengtianspringboot.Controller;

import com.example.mengtianspringboot.Pojo.Result;
import com.example.mengtianspringboot.Pojo.Student;
import com.example.mengtianspringboot.Serice.StudentService;
import com.example.mengtianspringboot.utils.JwtUtil;
import com.example.mengtianspringboot.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能
 * 作者：梦天
 * 日期：2023/11/18 14:59
 */
@RestController
@RequestMapping("/student")
@Validated
public class StudentController {

    @Autowired
    private StudentService studentService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        //查询
        Student student = studentService.findByStudentName(username);
        if (student == null){
            studentService.register(username,password);
            return Result.success();
        }else {
            return Result.error("账号已被注册");
        }
        //注册
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        Student loginStudent = studentService.findByStudentName(username);
        if (loginStudent == null){
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(password).equals(loginStudent.getStudentNumber())){
//            return Result.success("jwt token令牌...");
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginStudent.getStudentName());
            claims.put("username",loginStudent.getStudentNumber());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }
}
